import simplejson, urllib2, urllib

translateAPIUrl = "http://ajax.googleapis.com/ajax/services/language/translate"
geoAPIUrl = "http://maps.google.com/maps/geo?output=json&%s"

def translate(question, srcLang, toLang):
    params = ({"langpair" : "%s|%s" % (srcLang, toLang),
               "v": "1.0",
               "q": unicode(question).encode("utf-8") })
    request = urllib2.Request(translateAPIUrl, data = urllib.urlencode(params))
    response = simplejson.load(urllib2.urlopen(request))
    if response["responseStatus"] == 200:
        return response["responseData"]["translatedText"]
    return None

def getCountryCodeByLocation(locationName):
    return getCountryCodeFromGeoData(getGeoData(locationName))

def getGeoCoordinates(locationName, countryCode):
    isUa = countryCode is None or countryCode.upper() == "UA"
    if not isUa:
        locationName = translate(locationName, "uk", countryCode)
    geodata = getGeoData(locationName)
    if getCountryCodeFromGeoData(geodata) == "UA" if countryCode is None else countryCode.upper():
        return getValueByPath(geodata, ("Placemark", 0, "Point", "coordinates"))
    return None

def getGeoData(question):
    request = urllib2.Request(geoAPIUrl % urllib.urlencode( {"q" : unicode(question).encode("utf-8")}))
    response = simplejson.load(urllib2.urlopen(request))
    if response["Status"]["code"] == 200:
        return response
    return None

def getCountryCodeFromGeoData(geoData):
    return getValueByPath(geoData, ("Placemark", 0, "AddressDetails", "Country", "CountryNameCode"))

def getValueByPath(dictionary, path):
    if dictionary is None:
        return None
    for key in path:
        try:
            dictionary = dictionary[key]
        except KeyError:
            return None
    return dictionary
